package com.Interface.util;

import java.util.Random;

/**
 * 
 * 使用DES解密,参数：密文 uncryptStr,密钥 key
 */

public class EncryptUtil {
	
	
	public static String UncryptKey(String uncryptStr, String key) {
		int keyLen;
		int keyPos;
		int offset;
		String dest;
		int srcPos;
		int srcAsc;
		int tmpSrcAsc;
		String s_aa;

		keyLen = key.length();
		if (keyLen == 0)
			key = "Think Space";
		keyPos = 0;
		srcPos = 0;
		srcAsc = 0;
		if (uncryptStr == null) {
			return "";
		} else {
			if (uncryptStr.length() < 2) {
				return "";
			}
		}
		dest = "";
		s_aa = uncryptStr.substring(0, 2);
		offset = Integer.parseInt(s_aa, 16);
		srcPos = 2;
		do {
			srcAsc = Integer.parseInt(uncryptStr.substring(srcPos, srcPos + 2),
					16);
			if (keyPos < keyLen)
				keyPos = keyPos + 1;
			else
				keyPos = 1;
			byte[] tmpstr = key.getBytes();
			tmpSrcAsc = srcAsc ^ (int) tmpstr[keyPos - 1];
			if (tmpSrcAsc <= offset)
				tmpSrcAsc = 255 + tmpSrcAsc - offset;
			else
				tmpSrcAsc = tmpSrcAsc - offset;
			dest = dest + (char) tmpSrcAsc;
			offset = srcAsc;
			srcPos = srcPos + 2;

		} while (srcPos < uncryptStr.length());
		return dest;
	}
	//加密
	public static String encrypKeys(String src, String key) {
		
		 int KeyLen;
		 int KeyPos;
		 int offset;
		 String dest;
		 int SrcPos;
		 int SrcAsc;
		 int Range;
		Random random = new Random();

		KeyLen = key.length();

		if (KeyLen == 0) {
			key = "FJWTADMIN";
		}
		KeyPos = 0;
		Range = 255;
		offset = random.nextInt(Range);// 取随机数
		dest = String.format("%02x", offset);// 转换成16进制
		for ( SrcPos = 0; SrcPos < src.length(); SrcPos++) {

			String str = src.substring(SrcPos);
			
			int acs = (int) str.charAt(0);// 取asc码

			SrcAsc = (acs + offset) % 255;
			if (KeyPos < KeyLen) {
				KeyPos = KeyPos + 1;
			} else {
				KeyPos = 1;
			}
			byte[] tmpstr = key.getBytes();// 取字节

			SrcAsc = SrcAsc ^ (int) tmpstr[KeyPos - 1];// 进行异或

			dest = dest + (String.format("%02x", SrcAsc));

			offset = SrcAsc;
			
			

		}

		return shift(dest);
	}

	public static String shift(String str) {
		int size = str.length();
		char[] chs = str.toCharArray();
		for (int i = 0; i < size; i++) {
			if (chs[i] <= 'Z' && chs[i] >= 'A') {
				chs[i] = (char) (chs[i] + 32);
			} else if (chs[i] <= 'z' && chs[i] >= 'a') {
				chs[i] = (char) (chs[i] - 32);
			}
		}
		return new String(chs);
	}
	public static void main(String[] args) {
		System.out.println(encrypKeys("yxxhuangql350426","yxxhuangql"));;
	}
	
}
